﻿IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_CreateOrUpdateJPushMessageLogV3]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_CreateOrUpdateJPushMessageLogV3]
GO

CREATE PROCEDURE [dbo].[sp_CreateOrUpdateJPushMessageLogV3](
    @MessageId INT,
    @Audience XML,    
    @Platform INT,
    @AppMessage XML,
    @Notification XML,
    @ResponseCode INT,
    @ResponseMessage NVARCHAR(MAX),
    @AndroidDeliveredCount INT,
    @ApplePushNotificationDeliveredCount INT,
    @WindowsPhonePushNotificationDeliveredCount INT,
    @IsTest BIT
)
AS

BEGIN
    DECLARE @Key AS UNIQUEIDENTIFIER;
    DECLARE @NowTime AS DATETIME = GETUTCDATE();

    IF @MessageId IS NOT NULL
    BEGIN

        SELECT @Key = [Key]
            FROM [dbo].[JPushMessageLogV3]
            WHERE [MessageId] = @MessageId;

        IF @Key IS NULL
        BEGIN
            SET @Key = NEWID();

             INSERT INTO [dbo].[JPushMessageLogV3]
               ([Key]
               ,[MessageId]
               ,[Audience]
               ,[Platform]
               ,[AppMessage]
               ,[Notification]
               ,[ResponseCode]
               ,[ResponseMessage]
               ,[AndroidDeliveredCount]
               ,[ApplePushNotificationDeliveredCount]
               ,[WindowsPhonePushNotificationDeliveredCount]
               ,[IsTest]
               ,[CreatedStamp]
               ,[LastUpdatedStamp])
         VALUES
               (@Key
               ,@MessageId
               ,@Audience
               ,@Platform
               ,@AppMessage
               ,@Notification
               ,@ResponseCode
               ,@ResponseMessage
               ,@AndroidDeliveredCount
               ,@ApplePushNotificationDeliveredCount
               ,@WindowsPhonePushNotificationDeliveredCount
               ,@IsTest
               ,@NowTime
               ,@NowTime);
        END
        ELSE
        BEGIN
            UPDATE [dbo].[JPushMessageLogV3]
                SET 
                    [ApplePushNotificationDeliveredCount] = @ApplePushNotificationDeliveredCount,
                    [AndroidDeliveredCount] = @AndroidDeliveredCount,
                    [WindowsPhonePushNotificationDeliveredCount] = @WindowsPhonePushNotificationDeliveredCount,
                    [LastUpdatedStamp] = @NowTime
                WHERE [Key] = @Key;
        END
    END 
END
GO